<template>
    <div class="user_manage_span">
        <table-span
                :current-page="tableData.current"
                :page-size="tableData.size"
                :total="tableData.total"
                :isShowTool="false"
                :size-change="handleSizeChange" 
                :current-change="handleCurrentChange">
            <template v-slot:searchItem>
                <div class="search_item_span search_item_fix_width">
                    <el-input size="default" v-model="userSearchCondition.code"
                        placeholder="请输入工号" clearable></el-input>
                </div>
                <div class="search_item_span search_item_fix_width">
                    <el-input size="default" v-model="userSearchCondition.nickname"
                        placeholder="请输入姓名" clearable></el-input>
                </div>
                <div class="search_item_span">
                    <el-button icon="Search" size="default" type="primary" @click="searchUserData">查询</el-button>
                </div>
                <div class="search_item_span">
                    <el-button icon="Plus" size="default"
                        type="primary" :disabled="!(btOption.btSaveUser)"
                        @click="openUserDialog(null, null)">新增用户</el-button>
                </div>
            </template>
            <template v-slot:searchTable>
                <el-table :data="tableData.records"
                    size="default" height="100%" style="width: 100%;">
                    <el-table-column
                        align="center"
                        type="index"
                        width="50">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="code"
                        label="员工工号"
                        width="190">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="nickname"
                        label="员工姓名"
                        width="190">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="mail"
                        label="邮箱地址"
                        min-width="190">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="deptNames"
                        label="部门信息"
                        width="190">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="createTime"
                        label="创建时间"
                        width="190">
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        align="center"
                        label="操作"
                        width="320">
                        <template #default="scope">
                            <el-button size="small" type="success" :disabled="!(btOption.btUpdateUserRole)"
                                @click="showUserRoleListDialog(scope.$index, scope.row)">设置角色</el-button>
                            <el-button size="small" type="danger" :disabled="!(btOption.btResetPassword)"
                                @click="resetPassword(scope.$index, scope.row)">重置密码</el-button>
                            <el-button size="small" :disabled="!(btOption.btUpdateUser)"
                                @click="openUserDialog(scope.$index, scope.row)">编辑</el-button>
                            <el-button size="small" type="danger"  :disabled="!(btOption.btDeleteUser)"
                                @click="btDeleteUser(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
        </table-span>
        <el-dialog
            v-model="userDialogOption.show"
            :title="userDialogOption.title"
            width="450px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :before-close="userDialogBeforeClose"
            @close="userDialogClose">
                <el-form
                    ref="userFormRef"
                    :model="userDataForm"
                    :rules="userFormRules"
                    label-width="80px"
                    status-icon
                >
                <el-form-item label="员工工号" prop="code">
                    <el-input v-model="userDataForm.code" placeholder="请填写员工工号" :clearable="true" :disabled="!userDialogOption.canChangeCode"></el-input>
                </el-form-item>
                <el-form-item label="员工昵称" prop="nickname">
                    <el-input v-model="userDataForm.nickname" placeholder="请填写员工昵称" :clearable="true"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="tel">
                    <el-input v-model="userDataForm.tel" placeholder="请填写手机号" :clearable="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱地址" prop="mail">
                    <el-input v-model="userDataForm.mail" placeholder="请填写邮箱地址" :clearable="true"></el-input>
                </el-form-item>
                <el-form-item label="部门信息" prop="deptIdList">
                    <el-tree-select
                        v-model="userDataForm.deptIdList"
                        :data="deptTreeList"
                        multiple
                        value-key="deptId"
                        :props="{label: 'deptName'}"
                        check-strictly
                        :render-after-expand="false"
                        :check-on-click-node="true"
                        show-checkbox
                        style="width: 330px"
                        clearable
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="userDialogBeforeClose">取消</el-button>
                    <el-button type="primary" @click="confirmUserDialog">
                        保存
                    </el-button>
                 </span>
            </template>
        </el-dialog>

        <!-- 用户角色列表 -->
        <el-dialog
            v-model="userRoleDialogOption.show"
            title="设置角色"
            width="620px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            @open="userRoleDialogOpen"
            @close="userRoleDialogClose">
            <el-form :inline="true" :model="userRoleDataForm" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="userRoleDataForm.roleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item>
                    <el-button icon="Search" size="default" type="primary" @click="searchUserRoleData">查询</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="userRoleTableData.records"
                size="default" max-height="470px" style="width: 100%;">
                <el-table-column
                    align="center"
                    type="index"
                    width="50">
                </el-table-column>
                <el-table-column
                    align="center"
                    prop="roleName"
                    label="角色名称"
                    width="190">
                </el-table-column>
                <el-table-column
                    fixed="right"
                    align="center"
                    label="授权"
                    width="320">
                    <template #default="scope">
                        <el-switch
                            v-model="scope.row.authorityStatus"
                            inline-prompt
                            :active-value=1
                            :inactive-value=0
                            active-text="是"
                            inactive-text="否"
                            :loading="scope.row.loading"
                            style="--el-switch-on-color: #409eff; --el-switch-off-color: #f56c6c"
                            :before-change="beforeSaveUserRole.bind(this, scope.row)"
                            :disabled="!btOption.btUpdateUserRole"
                        />
                    </template>
                    </el-table-column>
            </el-table>
            <div class="user_role_page">
                <el-pagination
                v-model:current-page="userRoleTableData.current"
                v-model:page-size="userRoleTableData.size"
                :page-sizes="[10, 50, 100, 150, 200]"
                :small="true"
                :disabled="false"
                :background="false"
                layout="total, sizes, prev, pager, next"
                :total="userRoleTableData.total"
                @size-change="userRoleSizeChange"
                @current-change="userRoleCurrentChange"
                />
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import TableSpan from '@/components/table-span.vue';
    import {tool} from "@/js/tool.js";
    import { ElMessage } from 'element-plus'

    export default {
        name: "userManage",
        data: function() {
            return {
                btOption: {
                    btSaveUser: null,
                    btUpdateUser: null,
                    btDeleteUser: null,
                    btUpdateUserRole: null,
                    btResetPassword: null
                },
                userSearchCondition: {
                    code: "",
                    nickname: "",
                    page: 1,
                    size: 10
                },
                tableData: {
                    total: 0,
                    size: 10,
                    current: 1,
                    records: []
                },
                userDataForm: {
                    userId: null,
                    code: "",
                    nickname: "",
                    tel: "",
                    mail: "",
                    deptIdList: []
                },
                userFormRules: {
                    code: [
                        { required: true, message: '请填写员工工号', trigger: 'blur' },
                        { max: 20, message: '工号不能超过20个字符', trigger: 'blur' }
                    ],
                    nickname: [
                        { required: true, message: '请填写员工昵称', trigger: 'blur' },
                        { max: 20, message: '昵称不能超过20个字符', trigger: 'blur' },
                    ],
                    mail: [
                        { type: 'email', message: '请填写正确的邮箱地址', trigger: 'blur' }
                    ]
                },
                userDialogOption: {
                    show: false,
                    type: 0, //0新增；1修改
                    title: "",
                    canChangeCode: false
                },
                userRoleTableData: {
                    total: 0,
                    size: 10,
                    current: 1,
                    records: []
                },
                userRoleDataForm: {
                    userId: null,
                    roleName: "",
                    page: 1,
                    size: 10
                },
                userRoleDialogOption: {
                    show: false,
                    selectData: null
                },
                deptTreeList: null
            }
        },
        methods: {
            searchUserData: function(){
                getUserList(this, this.userSearchCondition);
            },
            handleSizeChange: function(val){
                this.userSearchCondition.size = val;
                this.userSearchCondition.page = 1;
                getUserList(this, this.userSearchCondition);
            },
            handleCurrentChange: function(val){
                this.userSearchCondition.page = val;
                getUserList(this, this.userSearchCondition);
            },
            btDeleteUser: function(index, row){
                const obj = this;
                const confirmMessage = "是否删除当前选择的用户：" + row.code + "?";
                this.$confirm(confirmMessage).then(function(){
                    const param = {
                        userId : row.userId
                    };
                    deleteUser(obj,param);
                }).catch(function(){

                });
            },
            openUserDialog: function(index, row) {
                if(row == null){
                    //新增
                    this.userDialogOption.type = 0;
                    this.userDialogOption.title = "新增用户";
                    this.userDialogOption.canChangeCode = true;
                }else{
                    //修改
                    this.userDialogOption.type = 1;
                    this.userDialogOption.title = "编辑用户";
                    this.userDialogOption.canChangeCode = false;
                    this.userDataForm = {
                        userId: row.userId,
                        code: row.code,
                        nickname: row.nickname,
                        tel: row.tel,
                        mail: row.mail,
                        deptIdList: row.deptIdList
                    }
                }
                this.userDialogOption.show = true;
            },
            userDialogBeforeClose: function() {
                userDialogCloseTips(this);
            },
            confirmUserDialog: function() {
                const obj = this;
                this.$refs["userFormRef"].validate(function(valid) {
                    if(valid) {
                        if(obj.userDialogOption.type == 0){
                            //新增
                            saveUser(obj, obj.userDataForm);
                        }else{
                            //修改
                            updateUser(obj, obj.userDataForm);
                        }
                    }
                })
                
            },
            userDialogClose: function(){
                this.userDataForm = {
                    userId: null,
                    code: "",
                    nickname: "",
                    tel: "",
                    mail: "",
                    deptIdList: []
                };
                this.$refs["userFormRef"].clearValidate();
            },
            resetPassword: function(index, row){
                const confirmMessage = "是否重置" + row.code + "的密码，并将通过邮箱通知？";
                this.$confirm(confirmMessage).then(function(){
                    resetPassword(row);
                }).catch(function(){

                });
            },
            showUserRoleListDialog: function(index, row) {
                this.userRoleDialogOption.show = true;
                this.userRoleDialogOption.selectData = row;
                this.userRoleDataForm.userId = row.userId;
            },
            userRoleDialogOpen: function(){
                getUserRoleList(this, this.userRoleDataForm);
            },
            searchUserRoleData: function(){
                this.userRoleDataForm.page = 1;
                getUserRoleList(this, this.userRoleDataForm);
            },
            userRoleSizeChange: function(val){
                this.userRoleDataForm.size = val;
                this.userRoleDataForm.page = 1;
                getUserRoleList(this, this.userRoleDataForm);
            },
            userRoleCurrentChange: function(val){
                this.userRoleDataForm.page = val;
                getUserRoleList(this, this.userRoleDataForm);
            },
            userRoleDialogClose: function(){
                this.userRoleDataForm.roleName = null;
                this.userRoleDataForm.userId = null;
                this.userRoleTableData = {
                    total: 0,
                    size: 10,
                    current: 1,
                    records: []
                }
            },
            beforeSaveUserRole: function(row){
                row.loading = true;
                return new Promise((resolve, reject)=>{
                    updateUserRole(this, row, resolve, reject);
                });
            }
        },
        created: function() {
            const menuId = [this.$route.query.menuId];
            const obj = this;
            new tool.getAuthorisedRequest(menuId, this.btOption, function(){
                getUserList(obj, obj.userSearchCondition);
                getDeptList(obj, {});
            });
        },
        components: {
            TableSpan
        }
    }

    /**
     * 获取用户信息列表
     * @param app app对象
     * @param param 获取数据的列表
     */
    function getUserList(app,param){
        const url = "/user/list";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                app.tableData.total = data.data.total;
                app.tableData.size = data.data.size;
                app.tableData.current = data.data.current;
                app.tableData.records = data.data.records;
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
* 获取部门信息列表
* @param app app对象
* @param param 获取数据的列表
*/
function getDeptList(app,param){
    const url = "/user/dept/list";
    tool.formJsonRequest(url,param,null,function(data){
        if(data.code === "0000"){
            app.deptTreeList = data.data;
        }else{
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

    /**
     * 保存用户信息
     * @param app app对象
     * @param param 保存的数据
     */
    function saveUser(app, param) {
        const url = "/user/save";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                ElMessage({
                    showClose: true,
                    message: '保存用户成功',
                    type: 'success'
                });
                app.userSearchCondition.page = 1;
                getUserList(app, app.userSearchCondition);
                app.userDialogOption.show = false;
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 更新用户信息
     * @param app app对象
     * @param param 保存的数据
     */
    function updateUser(app, param) {
        const url = "/user/update";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                ElMessage({
                    showClose: true,
                    message: '更新用户成功',
                    type: 'success'
                });
                getUserList(app, app.userSearchCondition);
                app.userDialogOption.show = false;
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 查询所有角色列表，并根据用户显示拥有的角色
     * @param app app对象
     * @param param 查询
     */
    function getUserRoleList(app, param){
        const url = "/user/getUserRoleList";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                app.userRoleTableData.records = data.data.records;
                app.userRoleTableData.total =  data.data.total;
                app.userRoleTableData.size = data.data.size;
                app.userRoleTableData.current = data.data.current;
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 删除用户
     * @param app app对象
     * @param param 删除数据
     */
    function deleteUser(app, param){
        const url = "/user/delete";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                ElMessage({
                    showClose: true,
                    message: '删除用户成功',
                    type: 'success'
                });
                app.userSearchCondition.page = 1;
                getUserList(app, app.userSearchCondition);
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 重置用户密码
     * @param param 选中的用户信息
     */
    function resetPassword(param){
        const url = "/user/resetPassword";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                ElMessage({
                    showClose: true,
                    message: '重置密码成功，请提醒用户查看邮箱信息',
                    type: 'success'
                });
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 更新角色对应的接口权限
     * @param app app对象
     * @param dataRow 请求的参数
     * @param resolve Promise 成功回调
     * @param reject Promise 失败回调
     */
    function updateUserRole(app, dataRow, resolve, reject){
        let authorityStatus = 0;
        if(dataRow.authorityStatus == 0){
            authorityStatus = 1;
        }else{
            authorityStatus = 0;
        }
        const param = {
            userId: app.userRoleDialogOption.selectData.userId,
            roleId: dataRow.roleId,
            authorityStatus: authorityStatus
        }
        const url = "/user/updateUserRole";
        tool.formJsonRequest(url,param,function(){
            dataRow.loading = false;
            reject(false);
        },
        function(data){
            dataRow.loading = false;
            if(data.code === "0000"){
                ElMessage({
                    showClose: true,
                    message: '更新用户对应角色成功',
                    type: 'success'
                });
                dataRow.authorityStatus = authorityStatus;
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 弹窗关闭时的提示信息
     * @param app
     */
     function userDialogCloseTips(app) {
        let confirmMessage = "";
        if(app.userDialogOption.type == 0){
            confirmMessage = "是否放弃新增用户？";
        }else{
            confirmMessage = "是否放弃编辑用户？"
        }
        app.$confirm(confirmMessage).then(function(){
            app.userDialogOption.show = false;
        }).catch(function(){

        });
    }
</script>
<style scoped>
    .user_manage_span{
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
        font-family: Microsoft YaHei,Heiti SC,tahoma,arial,Hiragino Sans GB,"\5B8B\4F53",sans-serif;
        flex-wrap : wrap;
    }
    .search_item_span{
        max-width: 190px;
        height: auto;
        margin-top: 5px;
        margin-left: 10px;
    }
    .search_item_fix_width{
        width: 190px;
    }
    .user_role_page{
        display: flex;
        align-self: flex-end;
        justify-content: flex-end;
        width: auto;
        height: auto;
        margin-top: 10px;
    }
</style>